import { useRef } from 'react';

import { useAntdTable, useRequest } from 'ahooks';
import { Button, Input, Table, Tag } from 'antd';

import Filter from '@/components/filter';
import Text from '@/components/text';

import { store } from '@/store';

import { usePermission } from '@/auth';
import {
  APIAuthTypeObj,
  APILogLevelObj,
  APIOpenTypeObj,
  APIRateLimitTypeObj,
  APITypeObj
} from '@/enum/api';
import {
  permissionApiReload,
  permissionApiTree
} from '@/services/base/quanxianmokuaihouduanjiekouxinxijiekou';

import Edit, { EditRef } from './edit';

/** 该模块增删改查对象 */
export type BizObject = BASE.ApiPermission;

const Page: React.FC = () => {
  const permission = usePermission();
  const edit = useRef<EditRef>(null);
  const [filter] = Filter.useForm();
  const table = useAntdTable(
    async (_, { ...formData }) => {
      const res = await permissionApiTree({
        ...formData
      });

      const list = res.data || [];

      return {
        list,
        total: list.length
      };
    },
    {
      form: filter
    }
  );
  // 刷新缓存
  const reloadCache = useRequest(
    async () => {
      await permissionApiReload();

      store.app?.message.success('刷新缓存成功');
      table.refresh();
    },
    {
      manual: true
    }
  );

  const onSearch = () => {
    table.search.submit();
  };

  const onReset = () => {
    table.search.reset();
  };

  return (
    <>
      {/* 筛选 */}
      <Filter
        onFinish={onSearch}
        form={filter}
        extra={
          <>
            <Button
              onClick={reloadCache.run}
              disabled={table.loading}
              loading={reloadCache.loading}
            >
              刷新缓存
            </Button>
          </>
        }
      >
        <Filter.Item name="name">
          <Input allowClear placeholder="请输入接口名称或者接口路径" style={{ width: 250 }} />
        </Filter.Item>

        <Filter.Item>
          <Button htmlType="submit" disabled={table.loading}>
            搜索
          </Button>
        </Filter.Item>

        <Filter.Item>
          <Button onClick={onReset} disabled={table.loading}>
            重置
          </Button>
        </Filter.Item>
      </Filter>
      {/* end 筛选 */}

      <Table<BizObject>
        rowKey="id"
        bordered
        size="small"
        expandable={{
          childrenColumnName: 'child'
        }}
        scroll={{
          x: 'max-content'
        }}
        columns={[
          {
            title: '权限名称',
            dataIndex: 'permissionName'
          },
          {
            title: '服务名称',
            dataIndex: 'serveName'
          },
          {
            title: '接口key',
            dataIndex: 'apiCode'
          },
          {
            title: '请求方式',
            dataIndex: 'requestWay'
          },
          {
            title: '接口地址',
            dataIndex: 'url'
          },
          {
            title: '权限类型',
            dataIndex: 'permissionType',
            render: (v) => {
              const obj = APITypeObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '状态',
            dataIndex: 'status',
            render: (v) => {
              const obj = APIAuthTypeObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '开放接口类型',
            dataIndex: 'apiType',
            render: (v) => {
              const obj = APIOpenTypeObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '是否限流',
            dataIndex: 'limitFlow',
            render: (v) => {
              const obj = APIRateLimitTypeObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '日志级别',
            dataIndex: 'logLevel',
            render: (v) => {
              const obj = APILogLevelObj.get(v);

              if (obj) {
                return <Tag color={obj.color}>{obj.text}</Tag>;
              }

              return emptyText;
            }
          },
          {
            title: '操作',
            fixed: 'right',
            align: 'center',
            render: (_, row) => {
              return (
                <Text.Space>
                  {permission.check() && (
                    <Text
                      onClick={() => {
                        edit.current?.open({
                          type: 'edit',
                          rowData: row,
                          onSuccess: () => {
                            table.refresh();
                          }
                        });
                      }}
                      type="primary"
                    >
                      编辑
                    </Text>
                  )}
                </Text.Space>
              );
            }
          }
        ]}
        {...table.tableProps}
        pagination={false}
      />

      <Edit ref={edit} />
    </>
  );
};

export default Page;
